import 'package:flutter/material.dart';

void main() {
  runApp(MainPage());
}
//父组件
class MainPage extends StatefulWidget {
  MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  List<String> _list = ["1","2","3","4","5","6","7","8","9","10"];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:Scaffold(
        body:GridView.count(crossAxisCount: 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        padding: EdgeInsets.all(10),
        children: List.generate(_list.length, (index) {
          return child(message:_list[index],index: index,onDelete: (index){
            print("调用父组件的删除方法，删除索引为$index");
            setState(() {
              _list.removeAt(index);
            });
          });
        }))
      )
    );
  }
}

//子组件
class child extends StatefulWidget {
  final String message;
  final int index;
  final Function(int) onDelete;
  child({Key? key,required this.message,required this.index,required this.onDelete}) : super(key: key);

  @override
  _childState createState() => _childState();
}

class _childState extends State<child> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topRight,
      children: [
        Container(
          alignment: Alignment.center,
          color: Colors.blue,
          child: Text("111-${widget.message}",
          style:TextStyle(color: Colors.white,fontSize: 20)),
        ),
        IconButton(color: Colors.white,onPressed: (){
          widget.onDelete(widget.index);
          
        }, icon: Icon(Icons.delete))
      ],
    );
  }
}